<template>
  <div class="main">
    <a-form
        id="formLogin"
        class="user-layout-login"
        ref="formLogin"
        :form="form"
        @submit="handleSubmit"
    >
      <a-tabs
          :activeKey="customActiveKey"
          :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
          @change="handleTabClick"
      >
        <!--        账号密码登录-->
        <a-tab-pane key="tab1" tab="账号密码登录">
          <a-alert v-if="isLoginError" type="error" showIcon style="margin-bottom: 24px;" message="用户信息有误" />
          <!--          用户名-->
          <a-form-item>
            <a-input
                size="large"
                type="text"
                placeholder="请输入用户名"
                v-decorator="[
                'username',
                {rules: [{ required: true, message: '用户名为必填项' }, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
              ]"
            >
              <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>
          <!--          密码-->
          <a-form-item>
            <a-input-password
                size="large"
                placeholder="请输入密码"
                v-decorator="[
                'password',
                {rules: [{ required: true, message: '密码为必填项' }], validateTrigger: 'blur'}
              ]"
            >
              <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input-password>
          </a-form-item>
        </a-tab-pane>
        <!--        邮箱登录-->
        <a-tab-pane key="tab2" tab="邮箱登录">
          <!--          邮箱-->
          <a-form-item>
            <a-input size="large" type="text" placeholder="请输入邮箱" v-decorator="['email', {rules: [{ required: true, pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '邮箱格式有误' }], validateTrigger: 'change'}]">
              <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
            </a-input>
          </a-form-item>
          <!--          验证码-->
          <a-row :gutter="16">
            <a-col class="gutter-row" :span="16">
              <a-form-item>
                <a-input size="large" type="text" placeholder="请输入验证码" v-decorator="['code', {rules: [{ required: true, message: '验证码为必填项' }], validateTrigger: 'blur'}]">
                  <a-icon slot="prefix" type="mobile" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                </a-input>
              </a-form-item>
            </a-col>
            <!--            获取验证码-->
            <a-col class="gutter-row" :span="8">
              <a-button
                  class="getCaptcha"
                  tabindex="-1"
                  :disabled="state.smsSendBtn"
                  @click.stop.prevent="getCaptcha"
                  v-text="!state.smsSendBtn && '获取验证码' || (state.time+' s')"
              ></a-button>
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs>
      <!--      记住我-->
      <a-form-item>
        <a-checkbox :disabled="true" v-decorator="['rememberMe', { valuePropName: 'checked' }]">自动登录</a-checkbox>
        <router-link
            :to="{ name: 'registerResult' }"
            class="forge-password"
            style="float: right;"
        > 激活用户 </router-link>
      </a-form-item>
      <!--      登录按钮-->
      <a-form-item style="margin-top:24px">
        <a-button
            size="large"
            type="primary"
            htmlType="submit"
            class="login-button"
            :loading="state.loginBtn"
            :disabled="state.loginBtn"
        > 登录 </a-button>
      </a-form-item>
      <!--      三方登陆-->
      <div class="user-login-other">
        <span> 其他方式 </span>
        <a @click="msg">
          <a-icon class="item-icon" type="alipay-circle"></a-icon>
        </a>
        <a @click="msg">
          <a-icon class="item-icon" type="taobao-circle"></a-icon>
        </a>
        <a @click="msg">
          <a-icon class="item-icon" type="weibo-circle"></a-icon>
        </a>
        <router-link class="register" :to="{ name: 'register' }"> 用户注册 </router-link>
      </div>
    </a-form>

    <two-step-captcha
        v-if="requiredTwoStepCaptcha"
        :visible="stepCaptchaVisible"
        @success="stepCaptchaSuccess"
        @cancel="stepCaptchaCancel"
    ></two-step-captcha>
  </div>
</template>

<script>
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import { getCaptcha } from "@/api/base";
import {getUserInfo, userLogin} from "@/api/user";
import {LOGIN_TOKEN, LOGIN_USER} from "@/constent";

export default {
  components: {
    TwoStepCaptcha
  },
  data () {
    return {
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type:  1 username, email
      loginType: 1,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      }
    }
  },
  methods: {
    // handler
    handleUsernameOrEmail (rule, value, callback) {
      const { state } = this
      state.loginType = 1
      callback()
    },
    // tabs激活改变回调
    handleTabClick (key) {
      // 修改当前登录方式
      this.customActiveKey = key
      this.loginType = key === 'tab1' ? 1 : 2;
    },
    // 提交回调
    handleSubmit (e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        customActiveKey
      } = this

      state.loginBtn = true

      const validateFieldsKey = customActiveKey === 'tab1' ? ['username', 'password'] : ['email', 'code']

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          const loginParams = { ...values }
          delete loginParams.username
          loginParams[state.loginType === 2 ? 'email' : 'username'] = values.username
          loginParams.loginType = this.loginType
          userLogin(loginParams)
              .then((res) => this.loginSuccess(res))
              .catch(err => this.requestFailed(err))
              .finally(() => {
                state.loginBtn = false
              })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 10)
        }
      })
    },
    // 获得验证码
    getCaptcha (e) {
      e.preventDefault()
      const { form: { validateFields }, state } = this

      validateFields(['email'], { force: true }, async (err, values) => {
        if (!err) {
          state.smsSendBtn = true

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = this.$message.loading('验证码发送中..', 0)

          // 获取验证码
          getCaptcha(values.email).then(res => {
            if (res.code === 200){
              setTimeout(hide, 2500)
              this.$notification['success']({
                message: '提示',
                description: '验证码获取成功,请查收',
                duration: 8
              })
            }else{
              this.$notification['error']({
                message: '提示',
                description: res.msg,
                duration: 8
              })
            }
          }).catch(err => {
            setTimeout(hide, 1)
            clearInterval(interval)
            state.time = 60
            state.smsSendBtn = false
            this.requestFailed(err)
          })
        }
      })
    },
    stepCaptchaSuccess () {
      this.loginSuccess()
    },
    stepCaptchaCancel () {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    // 将用户数据存放到localstore
    saveUserInfo(user,token){
      // 存用户信息
      localStorage.setItem(LOGIN_USER,JSON.stringify(user));
      localStorage.setItem(LOGIN_TOKEN,token);
    },
    // 登录成功处理
    loginSuccess (res) {
      if(res.code === 200){
        this.saveUserInfo(res.data.loginUser,res.data.token);
        // 存菜单
        this.$store.dispatch("saveMenuList",res.data.userMenus);
        this.$router.push({ path: '/admin' })
        // 延迟 1 秒显示欢迎信息
        setTimeout(() => {
          this.$notification.success({
            message: '欢迎',
            description: `${res.data.loginUser.realName}，欢迎回来`
          })
        }, 1000)
        this.isLoginError = false
      }else{
        this.$notification.error({
          message: '失败',
          description: `${res.msg}`
        })
      }
    },
    // 请求失败处理
    requestFailed (err) {
      this.isLoginError = true
      this.loginBtn = false;
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4
      })
    },
    msg(){
      this.$message.info('暂未开通,期待后续版本')
    }
  }
}
</script>

<style lang="less" scoped>
.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}
</style>
